package com.rongxun.http;

import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.PreferenceUtils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by nelon on 17-10-11.
 */

public class TokenInterceptor implements Interceptor {
    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
        Request originRequest = chain.request();

        Request.Builder builder = originRequest.newBuilder();

        String token = PreferenceUtils.getString(SPKey.TOKEN, "");

        //添加token
        builder.addHeader("Authorization", HttpConstants.Token_hold+token);

        //从request中获取header端口的值
        String portValue = originRequest.header("port");
        if (portValue != null) {
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            builder.removeHeader("port");
            HttpUrl newBaseUrl = HttpUrl.parse(HttpConstants.BASE_URL + ":" + portValue);
            FlyLog.i("builderUrl:"+newBaseUrl);
            //从request中获取原有的HttpUrl实例oldHttpUrl
            HttpUrl oldHttpUrl = originRequest.url();
            //重建新的HttpUrl，修改需要修改的url部分
            HttpUrl newUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    .build();
            return
                    chain.proceed(builder.url(newUrl).build());
        }else{
            HttpUrl newBaseUrl = HttpUrl.parse(HttpConstants.BASE_URL +HttpConstants.DEFAULT_PORT);
            FlyLog.i("builderUrl:"+newBaseUrl);
            //从request中获取原有的HttpUrl实例oldHttpUrl
            HttpUrl oldHttpUrl = originRequest.url();
            //重建新的HttpUrl，修改需要修改的url部分
            HttpUrl newUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    .build();
            return
                    chain.proceed(builder.url(newUrl).build());
        }
    }

}
